package com.ruoyi.project.order.wx;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.WXConstants;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class WxSender {

    @Autowired
    IUserService initUserService;

    public static IUserService iUserService;


    @PostConstruct
    public void init() {
        iUserService = initUserService;
    }


    public static String PostUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    private static String send(Integer userId, String templateId, Map<String, String> map) {
        System.out.println(PostUrl);
        User user = iUserService.selectUserById(userId.longValue());
        if (user == null) {
            return "用户不存在,请检查id";
        }
        String openId = user.getOpenId();
        if (openId == null) {
            return "该用户尚未绑定微信,请尽快通知他在公众号绑定";
        }
        JSONObject all = new JSONObject();
        all.put("touser", openId);
        all.put("template_id", templateId);
        Set<String> keys = map.keySet();
        JSONObject data = new JSONObject();
        for (String key : keys) {
            JSONObject value = new JSONObject();
            value.put("value", map.get(key));
            data.put(key, value);
        }
        all.put("data", data);
        System.out.println(user.toString());
        System.out.println(JSONUtil.formatJsonStr(all.toJSONString()));
        String result = HttpUtil.post(PostUrl + WXConstants.access_token, all.toJSONString());

        return result;
    }

    /**
     * 发送通知
     */
    public static String sendMsg(Integer userId, String templateId, Object... words) {
        Map<String, String> map = new HashMap<>();
        map.put("first", words[0]+"");
        for (int i = 1; i < words.length - 1; i++) {
            map.put("keyword" + i, words[i]+"");
        }
        map.put("remark", words[words.length - 1]+"");
        return send(userId, templateId, map);
    }




}
